package net.joint_painting.server.manager;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import net.joint_painting.server.model.MemCache;
import net.joint_painting.shared.model.Line;
import net.joint_painting.shared.model.Work;

/**
 * @author CAM
 * @version $Revision: 1.0 $
 */
public class WorkManager implements Serializable {

    /**
	 * 
	 */
    private static final long serialVersionUID = 7437647173819212570L;

    /**
     * Method addLine.
     * 
     * @param line
     *            Line
     */
    public static void addLine(Line line) {
	WorkManager manager = loadManager();
	List<Line> lines = manager.lines.get(line.getSurfaceId());
	if (lines == null)
	    lines = new LinkedList<Line>();
	lines.add(line);
	manager.lines.put(line.getSurfaceId(), lines);
	manager.save();
    }

    /**
     * Method getWork.
     * 
     * @return Work
     */
    public static Work getWork() {
	WorkManager manager = loadManager();

	Work work = null;
	if (manager.lines.size() > 0) {
	    work = new Work();
	    String key = (String) manager.lines.keySet().toArray()[0];
	    work.setId(key);

	    Work sentwork = manager.sentWork.get(key);
	    if (sentwork != null) {
		work.setLines(sentwork.getLines());
	    }
	    work.addLines(manager.lines.get(key));
	    manager.lines.remove(key);
	    manager.sentWork.put(key, work);
	    manager.save();
	}

	return work;
    }

    /**
     * Method handWork.
     * 
     * @param work
     *            Work
     */
    public static void handWork(Work work) {

	WorkManager manager = loadManager();
	Work sentWork = manager.sentWork.get(work.getId());
	if (sentWork != null && sentWork.getDate().equals(work.getDate())) {
	    manager.sentWork.remove(work.getId());
	    net.joint_painting.server.logic.Surface.drawSurface(work.getId(),
		    work.getSurface());
	    manager.save();
	}
    }

    /**
     * Method loadManager.
     * 
     * @return WorkManager
     */
    private static WorkManager loadManager() {
	WorkManager manager = (WorkManager) MemCache
		.getCached(WorkManager.class.getName() + serialVersionUID);
	if (manager == null)
	    manager = new WorkManager();
	return manager;
    }

    Map<String, List<Line>> lines = new HashMap<String, List<Line>>();

    Map<String, Work> sentWork = new HashMap<String, Work>();

    private WorkManager() {

    }

    private void save() {
	MemCache.cache(WorkManager.class.getName() + serialVersionUID, this);
    }

}
